package com.kkyy.msystem.controller;

import com.kkyy.msystem.entity.UsersEntity;
import com.kkyy.msystem.feign.FeignService2;
import com.kkyy.msystem.service.RegistService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RegistController {
    @Autowired
    RegistService registService;

    @Autowired
    FeignService2 feignService2;

    @RequestMapping("/regist")
    public String regist() {
        return "regist";
    }

    // 唯一从前端跳向后台的handler，vue注册后同步后台用户
    @CrossOrigin
    @RequestMapping("/msystemUsers")
    @ResponseBody
    public void insert(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("fullname") String fullname,
            @RequestParam("mobile") String mobile) {
        UsersEntity user = new UsersEntity();
        user.setFullname(fullname);
        user.setUsername(username);
        user.setMobile(mobile);
        SimpleHash pwd = new SimpleHash("MD5", password, username);
        user.setPassword(pwd.toString());
        user.setUsertype("0");
        registService.insertOne(user);
    }

    // 后台注册
    @RequestMapping("/regFin")
    @ResponseBody
    public String regFin(UsersEntity usersEntity) {
        // 用户名不能重复
        UsersEntity selOne = registService.getOneByUsername(usersEntity.getUsername());
        // 手机号是否符合规范
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        boolean result = usersEntity.getMobile().matches(regex);
        if (selOne != null) {
            return "该用户已存在！";
        } else if (result) {
            SimpleHash password = new SimpleHash("MD5", usersEntity.getPassword(), usersEntity.getUsername());
            usersEntity.setPassword(password.toString());
            registService.insertOne(usersEntity);
            // 前端用户同步
            feignService2.insertUsers(usersEntity.getUsername(), password.toString());
            return "注册成功！";
        } else {
            return "请输入真实的手机号！";
        }
    }
}